<template>
  <el-dialog
    v-model="dialogVisible"
    title="上传插件"
    width="500px"
    @close="handleClose"
  >
    <el-form :model="form" ref="formRef" :rules="rules" label-width="0">
      <el-form-item prop="file">
        <el-upload
          class="upload-area"
          drag
          action="#"
          :auto-upload="false"
          :limit="1"
          :on-change="handleFileChange"
          :on-exceed="handleExceed"
          :on-remove="handleRemove"
          :file-list="fileList"
          accept=".jar,.zip"
        >
          <el-icon class="upload-icon"><Upload /></el-icon>
          <div class="upload-text">
            <span>点击或拖拽文件到此处上传</span>
            <p class="upload-tip">支持 .jar 或 .zip 格式</p>
          </div>
          <template #tip>
            <div class="upload-tip">最大支持 100MB 的插件文件上传</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitUpload" 
          :loading="uploading" 
          :disabled="!hasFile"
        >
          上传
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { Upload } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { UploadInstance, UploadFile, UploadUserFile } from 'element-plus'
import { uploadPlugin } from '@/api/plugin'

interface Props {
  visible: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void
  (e: 'upload-success', plugin: any): void
}>()

// 对话框显示状态
const dialogVisible = ref(false)

// 表单状态
const form = ref({
  file: null as File | null
})
const formRef = ref()
const rules = {
  file: [
    { required: true, message: '请选择要上传的插件文件', trigger: 'change' }
  ]
}

// 文件上传状态
const fileList = ref<UploadUserFile[]>([])
const uploading = ref(false)
const hasFile = computed(() => fileList.value.length > 0)

// 监听visible属性变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val
  if (!val) {
    resetForm()
  }
})

// 监听对话框状态变化
watch(() => dialogVisible.value, (val) => {
  emit('update:visible', val)
})

// 处理文件变化
const handleFileChange = (uploadFile: UploadFile) => {
  // 判断文件大小（限制为100MB）
  const isLt100M = uploadFile.size / 1024 / 1024 < 100
  if (!isLt100M) {
    ElMessage.error('上传文件大小不能超过 100MB!')
    fileList.value = []
    form.value.file = null
    return
  }
  
  // 更新文件列表和表单数据
  fileList.value = [uploadFile]
  form.value.file = uploadFile.raw || null
}

// 处理文件超出限制
const handleExceed = () => {
  ElMessage.warning('最多只能上传1个文件')
}

// 处理文件移除
const handleRemove = () => {
  fileList.value = []
  form.value.file = null
}

// 提交上传
const submitUpload = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid && form.value.file) {
      uploading.value = true
      
      try {
        // 调用上传API
        const response = await uploadPlugin(form.value.file)
        
        ElMessage.success('插件上传成功')
        emit('upload-success', response)
        dialogVisible.value = false
      } catch (error) {
        console.error('上传失败:', error)
        ElMessage.error(`上传失败：${error instanceof Error ? error.message : '请重试'}`)
      } finally {
        uploading.value = false
      }
    }
  })
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 重置表单
const resetForm = () => {
  nextTick(() => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
    fileList.value = []
    form.value.file = null
  })
}
</script>

<style scoped>
.upload-area {
  display: block;
  width: 100%;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 10px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 6px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
}

:deep(.el-upload-list) {
  margin-top: 16px;
}
</style> 